﻿$(function() {
	 $("#baseTeacherForm").validate({
	        rules: {
	          name: {
	        	  required: true
	          },
	          age: {
	        	  required: true,
	        	  digits:true
	          },
	          headPic: {
	        	  required: true
	          }
	        }
	    });
	    
	// 图片预览	
	$("#abc").bind('change', function (e) {
        var imgBox = e.target;
        uploadImg($('#bcd'), imgBox)	    
	});
	
	// ajax上传头像
	$("#uploadButton").click(function(){
		$.ajaxFileUpload({
            url: 'upload.action', 
            type: 'post',
            secureuri: false, //一般设置为false
            fileElementId: 'abc', // 上传文件的id、name属性名
            dataType: 'text', //返回值类型，一般设置为json、application/json
            success: function(data, status){
            	console.log(data);
            	var response = JSON.parse(data);
				alert(response.msg);
            	if (response.success) {
					// 上传成功
            		$("#headPic").val(response.filePath);    
            		$("#abc").val("");
				}
            },
            complete:function(){
    			$("#abc").replaceWith("<input type='file' class='form-control' id='abc' name='abc'>");
    			
    			$("#abc").bind('change', function (e) {
    		        var imgBox = e.target;
    		        uploadImg($('#bcd'), imgBox)	    
    			});
    		},
            error: function(data, status, e){ 
            	console.log(data);
            	console.log(status);
            	console.log(e);
            }
        });
	})
})
	

/**
 * 预览图片
 * @param element
 * @param tag
 * @returns
 */
function uploadImg(element, tag) {
    var file = tag.files[0];
    var imgSrc;
    if (!/image\/\w+/.test(file.type)) {
        alert("看清楚，这个需要图片！");
        return false;
    }
    var reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function() {
    	element.html("")
        imgSrc = this.result;
        var imgs = document.createElement("img");
        $(imgs).attr("src", imgSrc);
        element.append(imgs);
    };
}